import json
import re
from collections import defaultdict

#解析出要的数据
def parse_log(log_file):
    process_times = defaultdict(list)

    with open(log_file, 'r') as file:
        for line in file:
            match = re.search(r"static_multistream\|frame_id:(\d+)\|timestamp:(-?\d+)\|cpu:(\d+)\|Process(A|B):(start|end):(\d+)", line)
            
            if match:
                frame_id = match.group(1)
                process_type = match.group(5)
                time = match.group(6)
                if process_type == "start":
                    process_times[frame_id].append({"start": time})
                elif process_type == "end":
                    process_times[frame_id][-1]["end"] = time

    return process_times

#计算
def calculate_metrics(process_times):
    process_a_times = []
    process_b_times = []
    frame_durations = []

    for frame_id, times in process_times.items():
        if len(times)==2:
            process_a_times.append(int(times[0]["end"])-int(times[0]['start']))
            process_b_times.append(int(times[1]["end"])-int(times[1]['start']))
            frame_durations.append(int(times[1]["end"]) - int(times[0]['start'])) #b的结束时间-a的开始时间
        else:
            process_a_times.append(int(times[0]["end"])-int(times[0]['start']))
            process_b_times.append(0)

    process_a_avg_time = sum(process_a_times) / len(process_a_times)
    process_a_p99_time = sorted(process_a_times)[int(len(process_a_times) * 0.99)]
    process_a_p90_time = sorted(process_a_times)[int(len(process_a_times) * 0.9)]
    
    len_b = len(list(filter(lambda x: x != 0, process_b_times)))#过滤掉为0的和值
    process_b_avg_time = sum(process_b_times) / len_b
    process_b_p99_time = sorted(process_b_times)[int(len_b * 0.99)]
    process_b_p90_time = sorted(process_b_times)[int(len_b  * 0.9)]

    system_avg_frames = 1000/(process_a_avg_time+process_b_avg_time)
    avg_frame_durations = sum(frame_durations)/len(frame_durations)



    return {
        "ProcessA": {
            "average_time": process_a_avg_time,
            "p99_time": process_a_p99_time,
            "p90_time": process_a_p90_time
        },
        "ProcessB": {
            "average_time": process_b_avg_time,
            "p99_time": process_b_p99_time,
            "p90_time": process_b_p90_time
        },
        "System Average Throughput":system_avg_frames,
        "Average Frame":avg_frame_durations
    }

# Main function
def main():
    log_file = "./trace_analysis.log"
    process_times = parse_log(log_file)
    metrics = calculate_metrics(process_times)

    with open('result.json', 'w') as outfile:
        json.dump(metrics, outfile, indent=4)

if __name__ == "__main__":
    main()
